package cn.ddcollection.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.io.FileUtils;
import org.jets3t.service.S3Service;
import org.jets3t.service.S3ServiceException;
import org.jets3t.service.ServiceException;
import org.jets3t.service.model.S3Object;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import cn.ddcollection.service.SSSService;

/**
 * @author 作者 E-mail:
 * @date 创建时间：2016年3月6日 上午9:33:24
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
@Service("sssService")
public class SSSServiceImpl implements SSSService {

	
	public Boolean uploadObject(CommonsMultipartFile file, String filename, String path, S3Service s3Service,
			String bucketName) {
		File destFile = new File(path);
		try {
			// FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作，不需要额外的再去关闭IO流
			FileUtils.copyInputStreamToFile(file.getInputStream(), destFile);// 复制临时文件到指定目录下
			// start upload file to S3
			File fileData = new File(path);
			// Create an empty object with a key/name, and print the object’s details.
			S3Object fileObject = new S3Object(fileData);
			//System.out.println("S3Object before upload: " + fileObject);
			// Upload the object to our test bucket in S3.
			s3Service.putObject(bucketName, fileObject);
			// Print the details about the uploaded object, which contains more information.  
			//System.out.println("S3Object after upload: " + fileObject);
			return true;
		} catch (IOException | NoSuchAlgorithmException | S3ServiceException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public void downloadObject(String bucketName, String objectName, S3Service s3Service) {
		try {
			String path = "F:/学习资料/测试文件/";
			FileWriter fw = new FileWriter(path+objectName);
			// Retrieve the HEAD of the data object we created previously.
			S3Object objectComplete = s3Service.getObject(bucketName, objectName);
			System.out.println("S3Object, details only: " + objectComplete);
			// Read the data from the object's DataInputStream using a loop,and
			// print it out
			BufferedReader reader = new BufferedReader(new InputStreamReader(objectComplete.getDataInputStream()));
			String data = null;
			while ((data = reader.readLine()) != null) {
//				System.out.println(data);
				fw.write(data);
			}
			fw.close();
			reader.close();
		} catch (IOException | ServiceException e) {
			e.printStackTrace();
		}
	}

}
